package net.qingchuan.sharing.algorithm;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;

public class TabComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {

    public TabComplexKeysShardingAlgorithm() {
    }

    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
        System.out.println("当前存在的表有:" + collection);
        Map columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        System.out.println("传入的参数列表:" + columnNameAndShardingValuesMap);
        //业务逻辑
        LinkedList cidList = (LinkedList)columnNameAndShardingValuesMap.get("cid");
        LinkedList userIdList = (LinkedList)columnNameAndShardingValuesMap.get("user_id");
        //此处根据获取到的值进行业务逻辑编写，如下仅做举例,如果没有传参则获取到的为null
        Long cid = (Long)cidList.get(0);
        Long userId = (Long)userIdList.get(0);
        if (cid > userId) {
            return Arrays.asList("course_2");
        } else if (cid < userId) {
            return Arrays.asList("course_1");
        } else {
            return Arrays.asList("course_1", "course_2");
        }
    }
}